package projectmanagement.console;

import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;

/**
 * @author Dmitry Toryanik
 *         <p/>
 *         This class provides a base logic for menu behavior.
 *         Has a methods directed to menu rendering and addition
 *         new menu options.
 */
class ConsoleMenu {
    /**
     * Inner class that contains single menu item.
     */
    private class MenuItem {
        private ConsoleMenuCallback callback;
        private String itemText;

        public MenuItem(String itemText, ConsoleMenuCallback callback) {
            this.itemText = itemText;
            this.callback = callback;
        }

        public ConsoleMenuCallback getCallback() {
            return callback;
        }

        public String getItemText() {
            return itemText;
        }
    }

    private List<MenuItem> items = new ArrayList<MenuItem>();

    public boolean add(String itemText, ConsoleMenuCallback callback) {
        return items.add(new MenuItem(itemText, callback));
    }

    public void show(String menuTitle) {
        int choose = 0;
        Scanner in = new Scanner(System.in);

        System.out.println("--------------");
        System.out.println(menuTitle);
        System.out.println("--------------");

        for (int i = 0; i < items.size(); i++) {
            MenuItem menuItem = items.get(i);
            System.out.printf("[%d] %s \n", i + 1, menuItem.getItemText());
        }

        System.out.print("\n>>>");

        try {
            choose = in.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("Selection must be an integer!");
        }

        if (choose > items.size() || choose < 1) {
            ConsoleManager.goBackHandler("Invalid selection!", in);
        } else {
            MenuItem menuItem = items.get(choose - 1);
            ConsoleMenuCallback callback = menuItem.getCallback();
            callback.invoke();
        }
    }

}
